const { app, BrowserWindow, Notification, Menu, MenuItem, globalShortcut, ipcMain, nativeTheme } = require('electron')
const path = require('path')

// Attribute
let win


// app init
app.whenReady()
  .then(() => {
    createWindow()
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
      }
    })
  })
  .then(showNotification)
  .then(addApplicationMenu)
  .then(addGlobalShortcut)

// 应用关闭
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 任务栏右键
app.setUserTasks([
  {
    program: process.execPath,
    arguments: '--new-window',
    iconPath: process.execPath,
    iconIndex: 0,
    title: 'New Window',
    description: 'Create a new window'
  }
])




/*                                     methods                                                       */
// 创建主窗口
function createWindow() {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true, // 是否集成 Nodejs
      nodeIntegrationInWorker: true,
      webSecurity: true,
      contextIsolation: false,
      preload: path.join(__dirname, '/src/main/preload.js'),
    }
  })
  win.loadFile(path.join(__dirname, '/src/render/index.html'))
  // 任务栏进度
  win.setProgressBar(0.5)
  ipcMain.handle('dark-mode:toggle', () => {
    if (nativeTheme.shouldUseDarkColors) {
      nativeTheme.themeSource = 'light'
    } else {
      nativeTheme.themeSource = 'dark'
    }
    return nativeTheme.shouldUseDarkColors
  })

  ipcMain.handle('dark-mode:system', () => {
    nativeTheme.themeSource = 'system'
  })
}

// 主进程通知
function showNotification() {
  const notification = {
    title: 'Basic Notification',
    body: 'Notification from the Main process'
  }
  new Notification(notification).show()
}

// 本地快捷键配置 顶部菜单栏
function addApplicationMenu() {
  const menu = new Menu()
  menu.append(new MenuItem({
    label: 'Electron',
    submenu: [{
      role: 'help',
      accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I',
      click: () => {
        console.log('Electron roks!')
      }
    }]
  }))
  Menu.setApplicationMenu(menu)
}

// 添加全局快捷键
function addGlobalShortcut() {
  globalShortcut.register('Alt+CommandOrControl+I', () => {
    win.webContents.openDevTools()
  })
}
